
//Copyright 1997-2009 Syrinx Development, Inc.
//This file is part of the Syrinx Web Application Framework (SWAF).
// == BEGIN LICENSE ==
//
// Licensed under the terms of any of the following licenses at your
// choice:
//
//  - GNU General Public License Version 3 or later (the "GPL")
//    http://www.gnu.org/licenses/gpl.html
//
//  - GNU Lesser General Public License Version 3 or later (the "LGPL")
//    http://www.gnu.org/licenses/lgpl.html
//
//  - Mozilla Public License Version 1.1 or later (the "MPL")
//    http://www.mozilla.org/MPL/MPL-1.1.html
//
// == END LICENSE ==
using System;
using System.Text.RegularExpressions;

namespace Swaf.Container
{
	/// <summary>
	/// Summary description for TimeExpireContainerNode.
	/// </summary>
	[Serializable]
	public class TimeExpireContainerNode : ExpireNodeBase
	{
		protected long m_timeoutTime;
		protected long m_timeToWait;
		protected bool m_sliding;

		public TimeExpireContainerNode(Match mr, params object[] extraInfo)
		{
			if(mr.Groups.Count == 4)
			{
				string type = mr.Groups[1].Value;
				double timeLength = Double.Parse(mr.Groups[2].Value);
				string timeType = mr.Groups[3].Value;

				m_sliding = (String.Compare(type, "after") == 0)?true:false;
				m_timeToWait = calcTime(timeLength, timeType);
				m_timeoutTime = DateTime.Now.Ticks + m_timeToWait;
				m_value = extraInfo[0];
			}
		}
		public override object get(string nameAddress, params object[] infoArgs)
		{
			if(m_sliding)
				m_timeoutTime = DateTime.Now.Ticks + m_timeToWait;			
			return base.get(nameAddress, infoArgs);
		}

		public override void put(string nameAddress, object val)
		{
			if (m_sliding)
				m_timeoutTime = DateTime.Now.Ticks + m_timeToWait;
			base.put(nameAddress, val);
		}

		protected long calcTime(double timeLength, string timeType)
		{
			long amountOfTime = 0;
			int oneSecond = 1000 * 10000; //.NET DateTime.Ticks uses 100 nanoseconds per "tick";
			IApplication app = Application.currentApp;
			if(app.resMgr.matches("{sec}", timeType).Success)
				amountOfTime = (long)(timeLength * oneSecond);
			else if(app.resMgr.matches("{minute}", timeType).Success)
				amountOfTime = (long)(timeLength * 60 * oneSecond);
			else if(app.resMgr.matches("{hour}", timeType).Success)
				amountOfTime = (long)(timeLength * 60 * 60 * oneSecond);
			else if(app.resMgr.matches("{day}", timeType).Success)
				amountOfTime = (long)(timeLength * 24 * 60 * 60 * oneSecond);

			return amountOfTime;
		}

		#region IExpireNode Members


		public override void check()
		{
			if(DateTime.Now.Ticks > m_timeoutTime)
				clear();
		}

		#endregion
	}
}
